'''
华夏嘟佩奇定期寿险
'''

import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests,execjs
from common.helper import Helper

class Spider( object ):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "华夏嘟佩奇定期寿险"

    #生成数据
    def genProductInfo(self):

        #年龄段
        years = [ str(i) for i in range(1,18)]

        #性别 0男 1女
        gender = ["0","1"]

        #有无社保 Y 有 N 没有
        socialSec = ["Y","N"]

        for v in product( years,gender,socialSec ):

            self.mysql.cursor.execute( domain["华夏嘟佩奇定期寿险"]["insert_sql"].format( v[0],v[1],v[2]))

            self.mysql._conn.commit()

            print("写入数据库成功")


    #执行爬虫
    def requestJson(self,dt=None):

        data = {

            "age":dt["year"],
            "isSocialSecurity":dt["socialSec"],
            "sex":dt["gender"]

        }

        r = requests.post( url = domain[ self.name ]["url"],headers=domain[self.name]["header"],data=data)

        if r.status_code == 200:

            price = self.parseAlgorithm( r.json() )

            totalPrice = Helper.decimalParse( price )

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":totalPrice

            }
            self.mysql.updatePrice( data )

        else:

            data = {

                "name":self.name,
                "id":dt["id"],
                "state":3,

            }

            self.mysql.updateTask( data )


    #算法解析
    def parseAlgorithm(self,ob):

        js = '''
            
            function parseAlgorithm( ob ) {
                
                s = Math.round(100 * ob.value.fjyl);
                t = Math.round(100 * ob.value.xxds);
                l = Math.round(100 * ob.value.xyztjyl);
                a = Math.round(100 * ob.value.sds);
                i = Math.round(100 * ob.value.xyztj);
                n = (s + 20 * t + l + 20 * a + 20 * i) / 100;
                return n
            }     
        
        '''

        cxt = execjs.compile( js )

        price = cxt.call("parseAlgorithm",ob)

        return price


    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":1
            }
            self.mysql.updateTask( data )

            self.requestJson( dt )

if __name__ == '__main__':

    s = Spider()
    s.main()

